/****************************************************
          File Name:svshm_xfr.h
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Tue 16 Sep 2014 07:36:24 PM CST
*****************************************************/

#include <sys/types.h>
#include<errno.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<fcntl.h>
#include <sys/stat.h>
#include <sys/sem.h>
#include <sys/mman.h>

#define WRITE_SEM 0
#define READ_SEM 1

#define LEN 1024
#define PATH "./tmp0309"
#define PERM (S_IWUSR|S_IRUSR|S_IWGRP|S_IRGRP)
#define SEM_KEY 0x0309

/********* semaphore initailize the following codes are from tlpi********/
union sem {
	int val;		// semaphore initailize
	struct semid_ds *buf;	// semaphore structure
	unsigned short *array;		// ? where to use ????
};

int Available(int semid, int semnum)
{
	union sem arg;
	
	arg.val=1;		// initailize semaphore to 1
	return semctl(semid,semnum,SETVAL,arg);
}

int Inuse(int semid, int semnum)
{
	union sem arg;
	
	arg.val=0;		// initailize to 0
	return semctl(semid,semnum,SETVAL,arg);
}

int reserve(int semid, int semnum)
{
	struct sembuf sops;
	
	sops.sem_num=semnum;
	sops.sem_op=-1;
	sops.sem_flg=0;
	
	while(semop(semid,&sops,1)==-1)
		if(errno!=EINTR)
			return -1;
	return 0;
}

int release(int semid, int semnum)
{
	struct sembuf sops;
	
	sops.sem_num=semnum;
	sops.sem_op=1;
	sops.sem_flg=0;
	
	return semop(semid,&sops,1);
}

/*********** I modified some of this orignal codes *********/

void err(char *fun)
{
    perror(fun);
    exit(errno);
}
